package com.lfy.springcloud.controller;


import com.lfy.springcloud.entities.CommonResult;
import com.lfy.springcloud.entities.Payment;
import com.lfy.springcloud.entities.PaymentDTO;
import com.lfy.springcloud.service.PaymentService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Api(value = "payment8001", tags = "payment接口")
@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {
    @Resource
    private PaymentService paymentService;
    @Value("${server.port}")
    private String serverPort;
    //服务注册与发现
    @Resource
    private DiscoveryClient discoveryClient;

    @ApiOperation(value = "add")
    @PostMapping("/add")
    public CommonResult<Integer> add(@RequestBody PaymentDTO dao) {
        Payment payment = new Payment();
        payment.setSerial(dao.getSerial());
        int add = paymentService.add(payment);
        log.info("插入payment->" + add);
        if (add > 0) {
            return new CommonResult(1, "插入payment成功" + serverPort, add);
        } else {
            return new CommonResult(0, "插入payment失败" + serverPort, add);
        }
    }

    @ApiOperation(value = "getById")
    @GetMapping("/getById")
    public CommonResult<Payment> getById(@RequestParam Long id) {
        Payment byId = paymentService.getById(id);
        return new CommonResult(1, "查询成功" + serverPort, byId);
    }

    @ApiOperation(value = "list")
    @GetMapping("/list")
    public CommonResult<Payment> list() {
        List<Payment> list = paymentService.list();
        return new CommonResult(1, "成功" + serverPort, list);
    }

    @GetMapping("/getDiscovery")
    public  CommonResult<Object> getDiscovery(){
        List<String> services= discoveryClient.getServices();
        for (String service : services) {
            log.info("service************"+service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info("instance++++++++++++"+instance.getServiceId()+"/"+instance.getPort()+"/"+instance.getUri());
        }
        return new CommonResult<>(1,"获取成功"+serverPort,this.discoveryClient);
    }
}
